package com.raft.core.log.snapshot;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;

import com.alibaba.com.caucho.hessian.io.HessianOutput;
import com.raft.core.node.NodeEndpoint;

public class FileSnapshotWriter implements AutoCloseable {

    private final DataOutputStream output;

    public FileSnapshotWriter(File file, int lastIncludedIndex, int lastIncludedTerm, Set<NodeEndpoint> lastConfig) throws IOException {
        this(new DataOutputStream(new FileOutputStream(file)), lastIncludedIndex, lastIncludedTerm, lastConfig);
    }

    FileSnapshotWriter(OutputStream output, int lastIncludedIndex, int lastIncludedTerm, Set<NodeEndpoint> lastConfig) throws IOException {
        this.output = new DataOutputStream(output);
        SnapshotHeader header = new SnapshotHeader(lastIncludedIndex, lastIncludedTerm, lastConfig);
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteOutput);
        hessianOutput.writeObject(header);
        byte[] headerBytes = byteOutput.toByteArray();
        this.output.writeInt(headerBytes.length);
        this.output.write(headerBytes);
    }

    public OutputStream getOutput() {
        return output;
    }

    public void write(byte[] data) throws IOException {
        output.write(data);
    }

    @Override
    public void close() throws IOException {
        output.close();
    }

}
